﻿(*
    The MIT License

    Copyright (c)2010 Fondevila Ltd

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*)


namespace uk.co.fondevila.GoGo

open System
open System.Net
open System.IO
open System.Text
open System.Xml
open System.ServiceModel.Syndication

open Exceptions

type internal GoGoSession (auth: string) =
    static let tokenUrl = "http://www.google.com/reader/api/0/token"
    let mutable _auth = auth
    
    member s.AuthToken
        with get() = _auth

    member s.getResponse(url: string, [<ParamArray>] parameters: GoGoParameter[]) =
        let mutable formattedParameters = ""
        for par in parameters do
            formattedParameters <- 
                formattedParameters + System.String.Format("{0}={1}&", par.Name, par.Value)
        formattedParameters <- formattedParameters.TrimEnd('&')

        let mutable request = null
        if formattedParameters.Length > 0 then
            request <- 
                WebRequest.Create(System.String.Format("{0}?{1}", url, formattedParameters)) :?> HttpWebRequest
        else 
            request <- WebRequest.Create(url) :?> HttpWebRequest

        request.Headers.Add("Authorization", "GoogleLogin auth=" + auth)

        try
            let response = request.GetResponse()
            match response with
            | :? HttpWebResponse as httpResponse->
                if httpResponse.StatusCode <> HttpStatusCode.OK then
                    raise(new GoGoResponseException(httpResponse.StatusCode, httpResponse.StatusDescription))
            | _ -> 
                raise(new GoGoResponseNullException())
            response
        with
        | _ as ex -> raise(new AuthTokenException(ex.Message))


    member s.postRequest(url: string, [<ParamArray>] postFields: GoGoParameter[]) =
        let mutable formattedParameters = ""
        for par in postFields |> Seq.filter (fun o -> o <> null) do
            formattedParameters <- System.String.Format("{0}={1}&", par.Name, par.Value)
        formattedParameters <- formattedParameters.TrimEnd('&')
        formattedParameters <- formattedParameters + System.String.Format("&{0}={1}", "T", s.getToken())
            
        let ascii = new ASCIIEncoding()
        let encodedPostData = ascii.GetBytes(System.String.Format(formattedParameters))
        let mutable request = HttpWebRequest.Create(url) :?> HttpWebRequest

        request.Method <- "POST"
        request.ContentType <- "application/x-www-form-urlencoded"
        request.ContentLength <- int64(encodedPostData.Length)
        request.Headers.Add("Authorization", "GoogleLogin auth=" + auth)

        use newStream = request.GetRequestStream()
        newStream.Write(encodedPostData, 0, encodedPostData.Length)

        let response = request.GetResponse() :?> HttpWebResponse
        if response.StatusCode <> HttpStatusCode.OK then
            raise(new LoginFailedException(response.StatusCode, response.StatusDescription))

    member s.getResponseStream(url: string, [<ParamArray>] parameters: GoGoParameter[]) =
        s.getResponse(url, parameters).GetResponseStream();

    member s.getSource(url: string, [<ParamArray>] parameters: GoGoParameter[]) =
        use reader = new StreamReader(s.getResponseStream(url, parameters))
        reader.ReadToEnd()

    member s.getToken() =
        s.getSource s.AuthToken

    member s.getFeed(url: string, [<ParamArray>] parameters: GoGoParameter[]) =
        use reader = new StreamReader(s.getResponseStream(url, parameters))
        use xmlReader = XmlReader.Create(reader, new XmlReaderSettings())

        SyndicationFeed.Load(xmlReader)



